<?php


namespace app\zhongmaotong\controller;


use app\zhongmaotong\model\SpucopyModel;
use app\zhongmaotong\model\SpuModel;
use app\zhongmaotong\validate\SpuValidate;
use cmf\controller\AdminBaseController;
use think\facade\Db;

class SpuController extends AdminBaseController
{public function index()
{
    // 获取搜索关键字
    $keyword = input('get.keyword', '');
    $where = [];
    if ($keyword) {
        $where[] = ['name', 'like', '%' . $keyword . '%'];
    }
    // 查询所有新闻并传递给视图
    $newsList = SpuModel::with(['spu'])
        ->where($where)
        ->order("list_order", 'desc')
        ->paginate(2); // 每页显示2条记录


    $page = $newsList->render();
    $this->assign('newsList', $newsList);
    $this->assign('page', $page);
    return $this->fetch();
}

    public function show($id)
    {
        $news = SpuModel::find($id);
        if($news['switch'] == 1){
            $news->switch = 0;
            if ($news->save()) {
                $this->success('编辑成功', url('Spu/index'));
            } else {
                $this->error('编辑失败');
            }
        }else{
            $news->switch = 1;
            if ($news->save()) {
                $this->success('编辑成功', url('Spu/index'));
            } else {
                $this->error('编辑失败');
            }
        }
    }


    public function add()
    {
        //查询班级
        $spu =SpucopyModel::select();

        return $this->fetch('add',[
            'spu' => $spu
        ]);
    }

    public function addPost()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
//                halt($data['image']);
            //验证数据
            $validate = new SpuValidate();
            $result = $validate->scene('add')->check($data);
            if (!$result) {
                return json(['code' => 0, 'msg' => $validate->getError(), 'data' => null]);
            }
//                $data['create_time'] = date('Y-m-d H:i:s');
            $data['images'] = implode(',',$data['images']);
            $result = SpuModel::create($data);
            if ($result) {
                $this->success('添加成功', url('Spu/index'));
            } else {
                $this->error('添加失败');
            }
        }
    }

    public function edit($id)
    {
        $news = SpuModel::find($id);
        if (!$news) {
            $this->error('商品不存在');
        }
        //查询班级
        $spu =SpucopyModel::select();

        $this->assign('news', $news);
        $this->assign('spu', $spu);

        return $this->fetch('edit');
    }

    public function editPost()
    {
        if ($this->request->isPost()) {
            $data = input('post.');

            //验证数据
            $validate = new SpuValidate();
            $result = $validate->scene('edit')->check($data);
            if (!$result) {
                return json(['code' => 0, 'msg' => $validate->getError(), 'data' => null]);
            }


            $news = SpuModel::find($data['id']);
            if (!$news) {
                $this->error('商品不存在');
            }
            // 处理内容中的图片地址
            //switch的默认值
            $data['switch'] = 1;

            $news->name = $data['name'];
            $news->image = $data['image'];
            $news->status = $data['status'];
            $news->gid = $data['gid'];
            $news->rmb = $data['rmb'];
            $news->zy = $data['zy'];
            $news->switch = $data['switch'];
            $news->update_time = date('Y-m-d H:i:s');
            if(empty($data['images'])) {
                if ($news->save()) {
                    $this->success('编辑成功', url('Spu/index'));
                } else {
                    $this->error('编辑失败');
                }
            }
            $data['images'] = implode(',',$data['images']);
            $news->images = $data['images'];
            if ($news->save()) {
                $this->success('编辑成功', url('Spu/index'));
            } else {
                $this->error('编辑失败');
            }



//            if($news->update($data)){
//                $this->success('修改成功','Spu/index');
//            }else{
//                $this->error('修改失败');
//            }
        }
    }


    public function delete($id)
    {
        $news = SpuModel::find($id);
        if (!$news) {
            $this->error('商品不存在');
        }

        if ($news->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function order()
    {
        parent::listOrders(new SpuModel());
        $this->success('排序成功');
    }

    //打开配置页面
    public function setGoodsAttr()
    {
        $spu_id = input('spu_id');
        $this->assign('spu_id',$spu_id);
        return $this->fetch('add_goods_attr2');
    }

    //配置提交
    public function setGoodsAttrPost()
    {
        $attrs = input('post.attr');
        $spuId = input('post.spu_id');
        if (count($attrs) < 1){
            $this->error('请至少配置一个属性！');
        }
        Db::name('spu_attr')->where('spu_id',$spuId)->delete();
        $insert_data = [];
        foreach ($attrs as $attr) {
            $insert_data[] = [
                'spu_id' => $spuId,
                'name' => $attr['name']
            ];
        }
        Db::name('spu_attr')->insertAll($insert_data);
        $this->success('保存成功');
    }

    //打开配置商品属性值页面
    public function setGoodsAttrValue()
    {

        $spu_id = input('spu_id');

        $this->assign('spu_id',$spu_id);

        return $this->fetch('add_goods_attr_value');
    }

    //提交表单
    public function setGoodsAttrValuePost()
    {
        $date = input('post.form');

        if (count($date) < 1){
            $this->error('请至少配置一个属性！');
        }
        $insert_data = [];
        foreach ($date as $attrs) {
            $insert_data[] = [
                'attr_id' => $attrs['attr'],
                'name' => $attrs['attr_value']
            ];
        }
        Db::name('spu_attr_value')->insertAll($insert_data);
        $this->success('保存成功');
    }

    //查询某个商品有哪些属性
    public function getGoodsAttr()
    {
        $spu_id = input('spu_id');
        //查询商品属性
        $attrs = Db::name('spu_attr')->where('spu_id',$spu_id)->select();
        return json(['code' => 1,'msg' => '商品属性','data' => $attrs]);

    }

    //查询某个商品有哪些属性
    public function getGoodsAttr2()
    {
        $spu_id = input('spu_id');
        //查询商品属性
        $attrs = Db::name('spu_attr')->where('spu_id',$spu_id)->select();
        return json(['code' => 1,'msg' => '商品属性','data' => $attrs]);

    }

    //打开配置页面
    public function setGoodsAttrs()
    {
        $spu_id = input('spu_id');
        $this->assign('spu_id',$spu_id);
        return $this->fetch('add_goods_attr3');
    }

    public function setGoodsAttrsPost()
    {
        $spu_id = input('post.spu_id');
        $form = input('post.form');
        \api\web\model\SpuModel::update([
            'attr' => json_encode($form,JSON_UNESCAPED_UNICODE)
        ],['id' => $spu_id] );
    }
}